/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cashmate.struts;

import com.cashmate.hibernate.dao.AreaDAO;
import com.cashmate.hibernate.dao.CollectionsDAO;
import com.cashmate.hibernate.dao.EmployeeDAO;
import com.cashmate.hibernate.dao.LoansDAO;
import com.cashmate.hibernate.dao.PaymentsDAO;
import com.cashmate.hibernate.pojo.Areas;
import com.cashmate.hibernate.pojo.Collections;
import com.cashmate.hibernate.pojo.Documents;
import com.cashmate.hibernate.pojo.Employees;
import com.cashmate.hibernate.pojo.Loans;
import com.cashmate.hibernate.pojo.Payments;
import com.cashmate.utilities.Denomination;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.validator.Valid;

/**
 *
 * @author Sarah
 */
public class SaveCollection extends ActionSupport implements ModelDriven<Collections> {

    @Valid
    private Collections coll;
    private Collections collsample;
    private AreaDAO ardao = (AreaDAO) ServletActionContext.getServletContext().getAttribute("areaDAO");
    private LoansDAO loan = (LoansDAO) ServletActionContext.getServletContext().getAttribute("loansDAO");
    private EmployeeDAO empdao = (EmployeeDAO) ServletActionContext.getServletContext().getAttribute("employeeDAO");
    private CollectionsDAO colldao = (CollectionsDAO) ServletActionContext.getServletContext().getAttribute("collectionsDAO");
    private PaymentsDAO paydao = (PaymentsDAO) ServletActionContext.getServletContext().getAttribute("paymentsDAO");
    private String cashonhand, totalc, cashshort;
    private String datecoll, acodecoll, ccodecoll;
    private String[] seriesname, bcodename, bnamename, receiptname, paymenttype;
    private String[] amountname;
    private String cshdepositnum;
    private int bankacctnum;
    private String cashdeposit;
    private String actstatus;
    private String loc;
    private String saved;
    private int sequence;
    private String status;
    private String view;
    //denomination
    private int thousand, fivehundred, twohundred, onehundred, fifty, twenty, ten, five, one = 0;

    public void setSequence(int sequence) {
        this.sequence = sequence;
    }

    public String getLoc() {
        return loc;
    }

    public String getActstatus() {
        return actstatus;
    }

    public void setActstatus(String actstatus) {
        this.actstatus = actstatus;
    }

    public void setPaymenttype(String[] paymenttype) {
        this.paymenttype = paymenttype;
    }

    public void setAmountname(String[] amountname) {
        this.amountname = amountname;
    }

    public void setBcodename(String[] bcodename) {
        this.bcodename = bcodename;
    }

    public void setBnamename(String[] bnamename) {
        this.bnamename = bnamename;
    }

    public void setReceiptname(String[] receiptname) {
        this.receiptname = receiptname;
    }

    public void setSeriesname(String[] seriesname) {
        this.seriesname = seriesname;
    }

    public void setAcodecoll(String acodecoll) {
        this.acodecoll = acodecoll;
    }

    public void setCcodecoll(String ccodecoll) {
        this.ccodecoll = ccodecoll;
    }

    public void setDatecoll(String datecoll) {
        this.datecoll = datecoll;
    }

    public void setBankacctnum(int bankacctnum) {
        this.bankacctnum = bankacctnum;
    }

    public void setCashdeposit(String cashdeposit) {
        this.cashdeposit = cashdeposit;
    }

    public void setCashonhand(String cashonhand) {
        this.cashonhand = cashonhand;
    }

    public void setCashshort(String cashshort) {
        this.cashshort = cashshort;
    }

    public void setCshdepositnum(String cshdepositnum) {
        this.cshdepositnum = cshdepositnum;
    }

    public void setTotalc(String totalc) {
        this.totalc = totalc;
    }

    public int getFifty() {
        return fifty;
    }

    public void setFifty(int fifty) {
        this.fifty = fifty;
    }

    public int getFive() {
        return five;
    }

    public void setFive(int five) {
        this.five = five;
    }

    public int getFivehundred() {
        return fivehundred;
    }

    public void setFivehundred(int fivehundred) {
        this.fivehundred = fivehundred;
    }

    public int getOne() {
        return one;
    }

    public void setOne(int one) {
        this.one = one;
    }

    public int getOnehundred() {
        return onehundred;
    }

    public void setOnehundred(int onehundred) {
        this.onehundred = onehundred;
    }

    public int getTen() {
        return ten;
    }

    public void setTen(int ten) {
        this.ten = ten;
    }

    public int getThousand() {
        return thousand;
    }

    public void setThousand(int thousand) {
        this.thousand = thousand;
    }

    public int getTwenty() {
        return twenty;
    }

    public void setTwenty(int twenty) {
        this.twenty = twenty;
    }

    public int getTwohundred() {
        return twohundred;
    }

    public void setTwohundred(int twohundred) {
        this.twohundred = twohundred;
    }

    public Collections getModel() {
        return coll;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getView() {
        return view;
    }

    public void setView(String view) {
        this.view = view;
    }

    @Action(value = "/save-coll", results = {
        @Result(name = "input", location = "${loc}"),
        @Result(name = "success", location = "${loc}"),
        @Result(name = "error", location = "${loc}")
    })
    @Override
    public String execute() {
        try {
            loc = "../../loancollection.jsp?cat=coll";

            Areas a = null;

            try {
                a = ardao.getByAreaCode(acodecoll);
            } catch (Exception e) {
                actstatus = "Pls provide a valid area code.";
                view = "yes";
                return ERROR;
            }

            DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
            Calendar cal = null;

            try {
                Date curdate = df.parse(datecoll);
                cal = Calendar.getInstance();
                cal.setTime(curdate);
                cal.add(Calendar.DATE, 1);
            } catch (Exception e) {
                actstatus = "Pls provide a valid date.";
                view = "yes";
                return ERROR;
            }



            //System.out.println("datenow:" + df.format(cal.getTime()));

            Documents document = new Documents();
            document.setDocumentno(null);
            document.setDocumenttype("official receipt");
            document.setDocumentdate(datecoll);
            document.isIsactive();

            Employees employee = empdao.getByIdNumber(ccodecoll);

            Collections collection = new Collections();

            if (cashonhand != null) {
                try {
                    double c = Double.parseDouble(removeComma(cashonhand));
                    collection.setCashonhand(c);
                } catch (Exception e) {
                    actstatus = "Pls provide a valid Undeposited Cash.";
                    view = "yes";
                    return ERROR;
                }
            }

            if (cashshort != null) {
                try {
                    double c = Double.parseDouble(removeComma(cashshort));
                    collection.setShort_(c);
                } catch (Exception e) {
                    actstatus = "Cash Short or Over is not valid";
                    view = "yes";
                    return ERROR;
                }
            }

            if (totalc != null) {
                try {
                    double c = Double.parseDouble(removeComma(totalc));
                    collection.setTotalamountcollected(c);
                } catch (Exception e) {
                    actstatus = "Total Collection is not valid";
                    view = "yes";
                    return ERROR;
                }
            }

            if (cashdeposit != null) {
                try {
                    double c = Double.parseDouble(removeComma(cashdeposit));
                    collection.setDepositamount(c);
                } catch (Exception e) {
                    actstatus = "Pls provide a valid Cash Deposited.";
                    view = "yes";
                    return ERROR;
                }
            }

            collection.setDocuments(document);
            collection.setAreas(a);
            collection.setDate(datecoll);
            collection.setEmployees(employee);
            collection.setDepositno(cshdepositnum);

            if (status.equals("save")) {
                collection.setStat("saved");
                loc = "../../loancollection.jsp?cat=savedcoll";
            } else if (status.equals("post")) {
                collection.setStat("posted");
                loc = "../../loancollection.jsp?cat=history";
            }

            List<Payments> paylist = new ArrayList<Payments>();
            Payments pym = null;
            double val = 0;

            HashMap<Integer, Double> loanlist = new HashMap<Integer, Double>();
            HashMap<Integer, Double> overduelist = new HashMap<Integer, Double>();
            HashMap<Integer, Integer> daysleftlist = new HashMap<Integer, Integer>();

            for (int i = 0; i < seriesname.length; i++) {
                Loans l = null;
                if (bcodename[i] != null) {
                    try {
                        int c = Integer.parseInt(bcodename[i]);
                        l = loan.getLoansByBorrowerUnique(c);
                    } catch (Exception e) {
                        actstatus = "Borrower ID is not valid.";
                        view = "yes";
                        return ERROR;
                    }
                }

                double balance = 0;
                try {
                    balance = l.getBalance();
                } catch (Exception e) {
                    actstatus = "Loan does not exist.";
                    view = "yes";
                    return ERROR;
                }

                if (amountname[i] != null) {
                    try {
                        val = Double.parseDouble(removeComma(amountname[i]));
                    } catch (Exception e) {
                        actstatus = "Payment entered not valid.";
                        view = "yes";
                        return ERROR;
                    }
                }

                balance = balance - val;
                loanlist.put(l.getLoanid(), balance);

                pym = new Payments();
                pym.setCollections(collection);
                pym.setLoans(l);
                pym.setAmount(val);
                pym.setType(paymenttype[i]);
                pym.setBalance(balance);

                if (receiptname[i] != null) {
                    try {
                        int c = Integer.parseInt(receiptname[i]);
                        pym.setReceiptno(c);
                    } catch (Exception e) {
                        actstatus = "Receipt Number entered not valid.";
                        view = "yes";
                        return ERROR;
                    }
                }

                if (seriesname[i] != null) {
                    try {
                        int c = Integer.parseInt(seriesname[i]);
                        pym.setSeriesno(c);
                    } catch (Exception e) {
                        actstatus = "Series no. entered not valid.";
                        view = "yes";
                        return ERROR;
                    }
                }

                Set<Payments> payset = l.getPaymentses();
                Iterator it = payset.iterator();

                double totalpay = 0;
                while (it.hasNext()) {
                    Payments element = (Payments) it.next();
                    totalpay = totalpay + element.getAmount();   //get total payments fr dbase
                }

                totalpay = totalpay + pym.getAmount();  // payment collected for this day
                //compute overdue   

                Date amortstart = df.parse(l.getStartofamort());
                long difference = (cal.getTime().getTime() - amortstart.getTime()) / (1000 * 60 * 60 * 24);
                double overdue = (difference * l.getAmortizationperday()) - totalpay;

                int daysleft = 100 - (int) difference;     //add 1 sa current day

                //daysleftlist.put(l.getLoanid(), difference);
                pym.setOverdue(overdue);
                paylist.add(pym);

                overduelist.put(l.getLoanid(), overdue);
                daysleftlist.put(l.getLoanid(), daysleft);

            }
            saved = colldao.saveCollection(collection, document, paylist, loanlist, overduelist, daysleftlist);

            Denomination denomination = new Denomination(thousand, fivehundred, twohundred, onehundred, fifty, twenty, ten, five, one);

            ServletActionContext.getRequest().setAttribute("collection", collection);
            ServletActionContext.getRequest().setAttribute("paylist", paylist);
            ServletActionContext.getRequest().setAttribute("document", document);
            ServletActionContext.getRequest().setAttribute("denomination", denomination);

            if (saved.equals("ok")) {
                actstatus = "ok";
            } else {
                actstatus = saved;
            }

            ServletActionContext.getRequest().setAttribute("savedeposit", actstatus);
            return SUCCESS;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
            actstatus = e.toString();
            System.out.println("SA SAVE DEPOSIT ETO" + e.toString());
        }
        return SUCCESS;
    }

    public String removeComma(String money) {
        String[] split = money.split(",");
        String splitstring = "";
        for (int j = 0; j < split.length; j++) {
            splitstring += split[j];
        }
        return splitstring;
    }
}
